import React, { Component } from 'react'

import TodoListUI from './TodoListUI'
import TodoItem from './TodoItem'
import store from '../store'
import { getInputChangeAction, getButtonClickAction, getDeleteClickAction, getList, getInitListAction } from '../store/action-creators'
import './style.css'

class TodoList extends Component {

  constructor (props) {
    super(props)

    this.state = {
      reduxData: store.getState(),
      testData: 666
    }
    
    this.storeChange = this.storeChange.bind(this)
    this.inputChange = this.inputChange.bind(this)
    this.buttonClick = this.buttonClick.bind(this)
    this.deleteClick = this.deleteClick.bind(this)

    store.subscribe(this.storeChange)
  }

  // 在组建即将被挂载到页面的时刻自动执行
  componentWillMount () {
    console.log('componentWillMount')
  }

  // 组将已经被挂载到页面后, 自动执行
  // axios获取数据都写在这里, 否则在其他生命周期执行, 可能会造成后面和 React Native 有冲突
  componentDidMount () {
    console.log('componentDidMount')
    // redux-saga 写法
    const action = getInitListAction()
    store.dispatch(action)
    
    // redux-thunk 写法
    // const action = getList()
    // store.dispatch(action)
  }

  // 组件被更新之前, 自动执行
  shouldComponentUpdate () {
    console.log('shouldComponentUpdate') 
    // 必须返回一个布尔值, 告诉react, 组件是否需要更新
    return true   
  }

  // 组件更新之前, shouldComponentUpdate之后自动执行
  componentWillUpdate () {
    console.log('componentWillUpdate') 
  }

  // 组件更新之后, 自动执行
  componentDidUpdate () {
    console.log('componentDidUpdate')
  }

  render () {
    return (
      <TodoListUI 
        reduxData={this.state.reduxData}
        inputChange={this.inputChange}
        buttonClick={this.buttonClick}
        deleteClick={this.deleteClick}
      />
    )            
  }

  storeChange () {
    this.setState(() => ({
      reduxData: store.getState()
    }))
  }

  getTodoItem () {
    return this.state.list.map((item, index) => (
      <TodoItem 
        key={index}
        item={item} 
        index={index} 
        deleteClick={this.deleteClick} />
    ))
  }

  inputChange (e) {
    const action = getInputChangeAction(e.target.value)
    store.dispatch(action)
  }

  buttonClick () {
    const action = getButtonClickAction(this.state.reduxData.inputValue)
    store.dispatch(action)
    // this.setState(prevState => ({
    //   list: [...prevState.list, prevState.inputValue],
    //   inputValue: ''
    // }), () => {
    //   // console.log(this.ul.childNodes.length)
    // })
  }

  deleteClick (index) {
    const action = getDeleteClickAction(index)
    store.dispatch(action)
    // this.setState(prevState => {
    //   const list = [...prevState.list]
    //   list.splice(index, 1)

    //   return {
    //     list
    //   }
    // })
  }
}

export default TodoList
